package com.example.lotterysystem.service.Impl;

import com.example.lotterysystem.service.PictureService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Component
//这个类的主要功能是提供一些工具方法或者辅助功能，而并非专门处理业务逻辑，那么将其视为一个通用组件更合适
public class PictureServiceImpl implements PictureService {
    @Value("${pic.local-path}")
    private String localPath;

    @Override
    public String savePicture(MultipartFile multipartFile) {
        //创建目录
        File dir = new File(localPath);
        if(!dir.exists()) {
            dir.mkdirs();
        }

        //创建索引
        // aaa.jpg -> xxx.jpg
        // aaa.jpg  拿到.jpg后缀 xxx 进行拼接为xxx.jpg
        String filename = multipartFile.getOriginalFilename();
        assert filename != null;
        String suffix = filename.substring(filename.lastIndexOf("."));
        filename = UUID.randomUUID() + suffix;

        //图片保存
        try {
            multipartFile.transferTo(new File(localPath + "/" + filename));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        return filename;
    }
}
